package com.cloudshop.service.common.mq;

import com.cloudshop.service.common.log.GlobalAccessLog;
import com.cloudshop.service.common.log.LogManager;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.stereotype.Component;

/**
 * 日志mq发送者.
 *
 * @author 宫新程
 * @since 2019/3/30 1:12
 */
@Slf4j
@Component
public class LogMqSender {

  private static final Logger logger = LoggerFactory.getLogger(LogManager.class);

  @Resource private AmqpAdmin amqpAdmin;
  @Resource private AmqpTemplate amqpTemplate;

  private static final String EXCHANGE_NAME = "cloud";

  /** 初始化mq发送者. */
  @PostConstruct
  public void initMq() {
    // 创建交换器
    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    amqpAdmin.declareExchange(exchange);

    String[] queuesName = new String[] {"log"};
    for (String queueName : queuesName) {
      Queue queue = new Queue(queueName, true);
      amqpAdmin.declareQueue(queue);
      log.info("初始化Queue:{},成功", queueName);

      Binding binding = BindingBuilder.bind(queue).to(exchange).with(queueName);
      amqpAdmin.declareBinding(binding);
      log.info("初始化Binding成功");
    }
  }

  /** 发送mq. */
  public void sendLogMq(GlobalAccessLog log) {
    logger.info("请求日志发送mq...");
    amqpTemplate.convertAndSend(EXCHANGE_NAME, "log", log);
    logger.info("请求日志发送mq成功...");
  }
}
